// import { useEffect, useState, useCallback } from 'react'
// import { getArticleListAPI } from '@/apis/article'
// import { Card, List, Pagination, Spin, Empty } from 'antd'
// import { Link } from 'react-router-dom'
// // 在文件顶部或其他合适位置导入图片
// import error from '@/assets/error.png'
// import background from '@/assets/background.png'

// // 然后在需要的地方使用，例如：
// const BlogHome = () => {
//   const [articles, setArticles] = useState([])
//   const [loading, setLoading] = useState(true)
//   const [pagination, setPagination] = useState({
//     current: 1,
//     pageSize: 6,
//     total: 0
//   })

//   const fetchArticles = useCallback(async () => {
//     try {
//       setLoading(true)
//       const res = await getArticleListAPI({
//         page: pagination.current,
//         per_page: pagination.pageSize
//       })
      
//       if (res && res.data) {
//         setArticles(res.data)
//         setPagination(prev => ({
//           ...prev,
//           total: res.total || res.data.length
//         }))
//       }
//     } catch (error) {
//       console.error('获取文章列表失败:', error)
//     } finally {
//       setLoading(false)
//     }
//   }, [pagination.current])

//   useEffect(() => {
//     fetchArticles()
//   }, [fetchArticles]) // 正确依赖项

//   const handlePageChange = (page) => {
//     setPagination(prev => ({ ...prev, current: page }))
//   }

//   return (
//     <div className="blog-home">
//       <div className="blog-header">
//         <h1>欢迎访问七安的博客</h1>
//         <div className="auth-links">
//           <Link to="/login">登录</Link>
//         </div>
//       </div>
      
//       {loading ? (
//         <Spin size="large" style={{ display: 'block', margin: '20px auto' }} />
//       ) : articles.length > 0 ? (
//         <>
//           <List
//             grid={{ gutter: 5, column: 2 }} 
//             dataSource={articles}
//             renderItem={article => (
//               <List.Item key={article.id}>
//                 <Card 
//                   title={<Link to={`/blog/${article.id}`}>{article.title}</Link>}
//                   extra={<span>{new Date(article.pubdate).toLocaleDateString()}</span>}>
//                   <div className="blog-preview">
//                     {/* 封面展示 */}
//                     <div className="cover">
//                       {(() => {
//                      const content = article.markdownContent || ''
//                      // 修改正则表达式以匹配方括号中的 URL
//                      const match =  content.replace(/\[|\]/g, '');
//                      console.log('match:', match)
//                      const imageUrl = match.replace('http://localhost:8080', '');
//                      console.log('imageUrl:', imageUrl)
//                      if (match && (match.startsWith('http') || match.startsWith('data:'))) {
//                        return (
//                          <img
//                            src={imageUrl}
//                            alt="封面"
//                            width={120}
//                            height={80}
//                            onError={(e) => {
//                              console.error('图片加载失败:', imageUrl)
//                              e.target.src = error
//                            }}
//                          />
//                        )
//                      }
                     
//                      return <img src={error} alt="无封面" width={120} height={80} />
//                       })()}
//                     </div>
            
//                     {/* 摘要内容 */}
//                     {article.summary && <p className="summary">{article.summary}</p>}
            
//                     {/* 元信息 */}
//                     <div className="meta">
//                       <span>作者: 七安 </span>
//                       <span>阅读数: {article.read_count}</span>
//                       <span>评论数: {article.comment_count}</span>
//                     </div>
//                   </div>
//                 </Card>
//               </List.Item>
//             )}
//           />
          
//           <Pagination
//             current={pagination.current}
//             pageSize={pagination.pageSize}
//             total={pagination.total}
//             onChange={handlePageChange}
//             style={{ textAlign: 'center', margin: '20px 0' }}
//           />
//         </>
//       ) : (
//         <Empty description="暂无文章" />
//       )}
//     </div>
//   )
// }

// export default BlogHome

import { useEffect, useState, useCallback } from 'react'
import { getArticleListAPI } from '@/apis/article'
import { Card, List, Pagination, Spin, Empty } from 'antd'
import { Link } from 'react-router-dom'
import error from '@/assets/error.png'
import background from '@/assets/background.png'

const BlogHome = () => {
  const [articles, setArticles] = useState([])
  const [loading, setLoading] = useState(true)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 6,
    total: 0
  })

  const fetchArticles = useCallback(async () => {
    try {
      setLoading(true)
      const res = await getArticleListAPI({
        page: pagination.current,
        per_page: pagination.pageSize
      })
      
      if (res && res.data) {
        setArticles(res.data)
        setPagination(prev => ({
          ...prev,
          total: res.total || res.data.length
        }))
      }
    } catch (error) {
      console.error('获取文章列表失败:', error)
    } finally {
      setLoading(false)
    }
  }, [pagination.current])

  useEffect(() => {
    fetchArticles()
  }, [fetchArticles])

  const handlePageChange = (page) => {
    setPagination(prev => ({ ...prev, current: page }))
  }

  return (
    <div className="blog-home">
      <div className="blog-header">
        <h1>七安 ' S Blog</h1>
        <div className="auth-links">
          <Link to="/login">登录</Link>
        </div>
      </div>
      
      <div className="blog-content">
        {loading ? (
          <Spin size="large" style={{ display: 'block', margin: '20px auto' }} />
        ) : articles.length > 0 ? (
          <>
            <List
              grid={{ gutter: 5, column: 2 }} 
              dataSource={articles}
              renderItem={article => (
                <List.Item key={article.id}>
                  <Card 
                    title={<Link to={`/blog/${article.id}`}>{article.title}</Link>}
                    extra={<span>{new Date(article.pubdate).toLocaleDateString()}</span>}>
                    <div className="blog-preview">
                      <div className="cover">
                        {(() => {
                          const content = article.markdownContent || ''
                          const match = content.replace(/\[|\]/g, '');
                          const imageUrl = match.replace('http://localhost:8080', '');
                          if (match && (match.startsWith('http') || match.startsWith('data:'))) {
                            return (
                              <img
                                src={imageUrl}
                                alt="封面"
                                width={200}
                                height={150}
                                onError={(e) => {
                                  console.error('图片加载失败:', imageUrl)
                                  e.target.src = error
                                }}
                              />
                            )
                          }
                          
                          return <img src={error} alt="无封面" width={200} height={150} />
                        })()}
                      </div>
                      
                      {article.summary && <p className="summary">{article.summary}</p>}
                      
                      <div className="meta">
                        <span>作者: 七安 </span>
                        <span>阅读数: {article.read_count}</span>
                        <span>评论数: {article.comment_count}</span>
                      </div>
                    </div>
                  </Card>
                </List.Item>
              )}
            />
            
            <Pagination
              current={pagination.current}
              pageSize={pagination.pageSize}
              total={pagination.total}
              onChange={handlePageChange}
              style={{ textAlign: 'center', margin: '20px 0' }}
            />
          </>
        ) : (
          <Empty description="暂无文章" />
        )}
      </div>
    </div>
  )
}

export default BlogHome